    package a12_图论;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;

    /**
     * <p>
     * a10_水流问题
     * </p>
     *
     * @author flyduck
     * @since 2025/4/24
     */
    public class a10_水流问题 {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);

            int rows = scanner.nextInt();
            int cols = scanner.nextInt();

            int[][] gird = new int[rows][cols];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    gird[i][j] = scanner.nextInt();
                }
            }


//            int rows = 5;
//            int cols = 5;
//
//            int[][] gird = new int[][]{
//                    {1,3,1,2,4},
//                    {1,2,1,3,2},
//                    {2,4,7,2,1},
//                    {4,5,6,1,1},
//                    {1,4,1,2,1}
//            };

            boolean[][] firstBorder = new boolean[rows][cols];
            boolean[][] secondBorder = new boolean[rows][cols];



            for (int i = 0; i < rows; i++) {
                dfs(gird, i, 0, firstBorder);//左
                dfs(gird, i, cols - 1, secondBorder);//右
            }

            for (int j = 0; j < cols; j++) {
                dfs(gird, 0, j, firstBorder);//上
                dfs(gird, rows - 1, j, secondBorder);//下
            }

            List<int[]> list = new ArrayList<>();
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if(firstBorder[i][j] && secondBorder[i][j]){
                        list.add(new int[]{i,j});
                    }
                }
            }

            for (int[] ints : list) {
                System.out.println(ints[0] + " " + ints[1]);
            }
        }

        public static final int[][] dirs = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};
        private static void dfs(int[][] gird, int x, int y, boolean[][] border) {
            if(border[x][y]){
                return;
            }
            border[x][y] = true;
            for (int[] dir : dirs) {
                int nextX = x + dir[0];
                int nextY = y + dir[1];
                if(nextX >= 0 && nextX < gird.length && nextY >= 0 && nextY < gird[0].length){
                    if(gird[nextX][nextY] >= gird[x][y]){
                        dfs(gird, nextX, nextY, border);
                    }
                }
            }
        }
    }
